package com.hebxy.ssm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hebxy.ssm.entity.Plan;
import com.hebxy.ssm.entity.User;
import com.hebxy.ssm.entity.UserCustom;
import com.hebxy.ssm.entity.jy1;
import com.hebxy.ssm.service.PlanService;
import com.hebxy.ssm.service.UserService;
@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	UserService userService;
	@Autowired
	PlanService planService;
	
	@RequestMapping(value="/role",method = {RequestMethod.GET,RequestMethod.POST})
	public String Role(HttpServletRequest request,ModelMap m,
			@RequestParam(value = "pageNum",required = false) Integer pageNum,
            @RequestParam(value = "pageSize",required = false) Integer pageSize){
		
		Integer num=1;
		Integer size=5;
		if(pageNum!=null&&!"".equals(pageNum)){
			num=pageNum;
		}
		if(pageSize!=null&&"".equals(pageSize)){
			size=pageSize;
		}
		
		PageHelper.startPage(num,size);
		
		List<User> users=userService.findUserList();
		for(User u:users){
			Plan plan=planService.findPlanById(u.getPlan_id());
			u.setPlanName(plan.getPlan_name());
			if(u.getStatus()==1){
				u.setStatusName("正常");
			}else{
				u.setStatusName("异常");
			}
		}
		PageInfo<User> pagehelper=new PageInfo<User>(users);
		m.put("pagehelper", pagehelper);
		String card = (String) request.getSession().getAttribute("username");
		System.out.println(card);
		User user=userService.findByCardNumber(card);
		if("admin".equals(user.getRole())){
			return "role";
		}else{
			m.put("msg","抱歉，你的权限不足，请联系管理员");
			return "user/index";
		}
		
		
		
	}
	@GetMapping("addUser")
	public String goToAdd(ModelMap m){
		kaHaoHeTaoCan(m);
		return "add_user"; 
	}
	@PostMapping("/addUser")
	public String addUser(@ModelAttribute("user") @Validated User user,BindingResult r,ModelMap m){
		if(r.hasErrors()){
			List<ObjectError> errors = r.getAllErrors();
			for(ObjectError error:errors){
				System.out.println(error.getDefaultMessage());
			}
			m.put("msg", "校验不合格 添加用户失败");
			m.put("errors", errors);
			kaHaoHeTaoCan(m);
			return "add_user";
		}
		Plan plan=planService.findPlanById(user.getPlan_id());
		if(user.getPrepaid_amount()<plan.getMonthly_fee()){
			m.put("msg2", "您预存的话费金额不足以支付本月固定套餐资费，请重新充值！");
			kaHaoHeTaoCan(m);
			return "add_user";
		}
		user.setBalance(user.getPrepaid_amount()-plan.getMonthly_fee());
		userService.addUser(user);
		m.put("msg1", "添加成功，可以点击此处前往用户管理页面");
		m.put("card_number", user.getCard_number());
		m.put("taocan", planService.findPlanById(user.getPlan_id()));
		return "add_user";
		
	}
	//生成卡号
	public void kaHaoHeTaoCan(ModelMap m){
	List<String> card_numbers =new ArrayList<>();
	for(int i=0;i<10;i++){
		String numb="139";
		for(int j=0;j<8;j++){
			numb=numb+new Random().nextInt(10);
		}
		User user=userService.findByCardNumber(numb);
		if(user!=null){
			i=i-1;
		}else{
			System.out.println(numb);
			card_numbers.add(numb);
		}
	}
	m.addAttribute("card_numbers", card_numbers);
	
	List<Plan> plans= planService.findPlanAll();
	m.addAttribute("plans",plans );
	}
	
	@GetMapping("/deleteUser")
	public String deleteUser(Integer id,ModelMap m){
		User user=userService.findUserById(id);
		System.out.println(user);
		if("admin".equals(user.getRole())){
			m.put("msg", "删除失败管理员账号不可删除");
			return "forward:/admin/role";
		}
		userService.deleteUserById(id);
		m.put("msg", "删除成功");
		return "forward:/admin/role";
	}
	@RequestMapping("/update_user")
	public String gotoUpdate(Integer id,ModelMap m){
		User user =userService.findUserById(id);
		if("admin".equals(user.getRole())){
			m.put("msg", "修改失败管理员账号不可修改");
			return "forward:/admin/role";
		}
		m.put("user", user);
		getPlan(m);
		return "update_user";
	}
	@RequestMapping("/updateUser")
	public String updateUser(@ModelAttribute("user") @Validated(value=jy1.class) User user,BindingResult r,HttpServletRequest request,ModelMap m){
		if(r.hasErrors()){
			List<ObjectError> errors=r.getAllErrors();
			for(ObjectError o:errors){
				System.out.println(o.getDefaultMessage());
			}
			m.put("errors", errors);
			getPlan(m);
			return "update_user";
		}
		Plan plan=planService.findPlanById(user.getPlan_id());
		if(user.getPrepaid_amount()<plan.getMonthly_fee()){
			m.put("yebz", "预存金额不足以支付套餐费用");
			getPlan(m);
			return "forward:/admin/update_user";
		}
		user.setBalance(user.getPrepaid_amount()-plan.getMonthly_fee());
		userService.updateUser(user);
		m.put("msg", "修改成功");
		return "forward:/admin/role";
	}
	public void getPlan(ModelMap m){
		List<Plan> planList=planService.findPlanAll();
		m.put("planList", planList);
	}
	
	@RequestMapping("/plsc")
	public String plsc(ModelMap m,
			@RequestParam(value = "pageNum",required = false) Integer pageNum,
            @RequestParam(value = "pageSize",required = false) Integer pageSize){
		
		Integer num=1;
		Integer size=5;
		if(pageNum!=null&&!"".equals(pageNum)){
			num=pageNum;
		}
		if(pageSize!=null&&"".equals(pageSize)){
			size=pageSize;
		}
		
		PageHelper.startPage(num,size);
		
		List<User> users=userService.findUserList();
		for(User u:users){
			Plan plan=planService.findPlanById(u.getPlan_id());
			u.setPlanName(plan.getPlan_name());
			if(u.getStatus()==1){
				u.setStatusName("正常");
			}else{
				u.setStatusName("异常");
			}
		}
		PageInfo<User> pagehelper=new PageInfo<User>(users);
		m.put("pagehelper", pagehelper); 
		return "plsc_user";
	}
	@RequestMapping("/deleteMulti")
	public String deleteMulti(Integer[] ids,ModelMap m){
		for(Integer i:ids){
			System.out.println(i);
			User user=userService.findUserById(i);
			if("admin".equals(user.getRole())){
				System.out.println(i);
				m.put("msg", "有管理员在内不可以删除");
				return "forward:/admin/plsc";
			}
		}
		Map<String,Object> map=new HashMap<>();
		map.put("ids", ids);
		userService.deleteUserByIds(map);
		m.put("msg", "批量删除成功");
		return "forward:/admin/plsc";		
	}
	
	@RequestMapping("/plxg")
	public String plxg(ModelMap m,
			@RequestParam(value = "pageNum",required = false) Integer pageNum,
            @RequestParam(value = "pageSize",required = false) Integer pageSize){
		
		Integer num=1;
		Integer size=5;
		if(pageNum!=null&&!"".equals(pageNum)){
			num=pageNum;
		}
		if(pageSize!=null&&"".equals(pageSize)){
			size=pageSize;
		}
		
		PageHelper.startPage(num,size);
		
		List<User> users=userService.findUserList();
		
		PageInfo<User> pagehelper=new PageInfo<User>(users);
		m.put("pagehelper", pagehelper);
		getPlan(m);
		return "plxg_user";
	}
	@RequestMapping("/updateAll")
	public String updateAll(UserCustom userCustom,ModelMap m){
		List<User> list=userCustom.getuList();
		for(User u:list){
			System.out.println(u);
			userService.updateUser(u);
		}
		m.put("msg", "修改成功");
		return "forward:/admin/plxg";
	}

	
	
}
